import { httpAsyncRequest } from "./http-service";
import apiUrl from "./apiUrl";

const urlmap = new Map(Object.entries(apiUrl));
let services = getService(urlmap);
// 将所有url注册为方法实例
function getService(urlmap) {
  const service = {};

  for (var [key, value] of urlmap) {
    if (isString(value)) {
      service[key] = createHttpAsyncRequestString(value);
    } else {
      const tempMap = new Map(Object.entries(value));

      if (tempMap.has("url")) {
        service[key] = createHttpAsyncRequestMap(value);
      } else {
        service[key] = getService(tempMap);
      }
    }
  }

  return service;
}

function createHttpAsyncRequestMap(mapOptions) {
  return function(options = {}) {
    return httpAsyncRequest(Object.assign(mapOptions, options));
  };
}

function createHttpAsyncRequestString(url) {
  return function(options = {}) {
    return httpAsyncRequest(
      Object.assign(
        {
          url: url
        },
        options
      )
    );
  };
}

function isString(str) {
  return typeof str == "string" && str.constructor == String;
}

// 将services挂载到vue的原型上
// 业务中引用的方法：this.$services.接口名（小驼峰）
// Object.defineProperty(Vue.prototype, '$services', {
//   value: services
// });

export default services;
